﻿using System.IO;
using System.Linq;
using MongoDB.Bson;
using MongoDB.Driver.GridFS;
using PicShare.Server.Repositories;
using ServiceStack.Common.Utils;

namespace PicShare.Server.Helpers
{
    public static class RepositoryExtentions
    {
        public static BsonObjectId AddFile(this UsersRepository repository, Stream inputStream, string fileName)
        {
            var fileInfo = repository.DbContext.Db.GridFS.Upload(inputStream, fileName);
            return (BsonObjectId)fileInfo.GetObjectId();
        }

        public static MongoGridFSFileInfo GetFile(this UsersRepository repository, BsonObjectId fileId)
        {
            MongoGridFSFileInfo file = repository.DbContext.Db.GridFS.FindOneById(fileId);
            return file;
        }

        public static void DeleteFile(this UsersRepository repository, string userName, string albumName, int index)
        {
            var user = repository.Find(usr => usr.UserName == userName);
            var userAlbum = user.Albums.First(alb => alb.Key == albumName).Value.ToList();
            var fileId = userAlbum[index];
            user.Albums.First(alb => alb.Key == albumName).Value.Remove(fileId);
            repository.DbContext.Db.GridFS.DeleteById(fileId);
            repository.Update(user);

        }
    }
}